# encoding: utf-8
"""

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lei.chang on '11/07/2025'
    comment: 视听会议相关
"""
import uuid
import time

from project.model import ResponseModel
from pydantic import BaseModel, Field
from project.database import DB_FOLDER


@ResponseModel
class ApiRoom(BaseModel):
    """
    """
    id: int = Field(0, title='房间id')
    code: int = Field(0, title='房间号')
    name: str = Field('', title='房间名称')
    user_a: str | None = Field(None, title='A参与者(名称)')
    user_b: str | None = Field(None, title='B参与者(名称)')
    user_id: str | None = Field(None, title='当前参与者')
    is_stop: bool = Field(False, title='是否停止')


@ResponseModel
class ApiToken(BaseModel):
    """
    """
    token: str


class ApiRecordingFile(BaseModel):
    """
    """
    name: str = Field('', title='文件名称')
    last_time: str = Field('', title='最后更新时间', description='%Y-%m-%d %H:%M:%S')
    url: str = Field('', title='链接')


@ResponseModel
class ApiRecordingFiles(BaseModel):
    """
    """
    files: list[ApiRecordingFile] | None = Field([], title='文件列表')


@ResponseModel
class ApiRecording(BaseModel):
    """
    """
    recording_id: str


class OrmModel(BaseModel):
    """
    """
    def commit(self):
        """
        :return:
        """
        try:
            with open(f'{DB_FOLDER}/{self.__class__.__tablename__}.data', 'r', encoding='utf-8') as f:
                data = f.readlines() or []
        except FileNotFoundError:
            data = []
        data = [v.strip('\n') for v in data]

        # 添加
        if not self.id:
            self.id = len(data) + 1
            data.append(str(self.model_dump()))
        else:
            data = [eval(v) for v in data]
            for v in data:
                if self.id != v['id']:
                    continue

                v.update(self.model_dump())
            data = [str(v) for v in data]

        with open(f'{DB_FOLDER}/{self.__class__.__tablename__}.data', 'w', encoding='utf-8') as f:
            f.writelines('\n'.join(data))

    @classmethod
    def query(cls, **kwargs) -> list[dict]:
        """
        :return:
        """
        records = []
        with open(f'{DB_FOLDER}/{cls.__tablename__}.data', 'r', encoding='utf-8') as f:
            """
            """
            for line in f.readlines():
                line = eval(line)
                if all(line[key] == value for key, value in kwargs.items()):
                    records.append(line)

        return records


class Room(OrmModel):
    """
    """
    __tablename__ = 'room'
    id: int = Field(0, title='房间id')
    code: int = Field(0, title='房间号')
    name: str = Field(..., title='房间名称')
    user_a: str | None = Field(None, title='A参与者(名称)')
    user_b: str | None = Field(None, title='B参与者(名称)')
    user_id: str | None = Field(None, title='当前参与者')
    recording_id: str | None = Field('', title='录音文件id')
    is_stop: bool = Field(False, title='是否停止')

    @classmethod
    def add(cls, **kwargs):
        """
        :param kwargs:
        :return:
        """
        room = cls(**kwargs)
        room.code = int(time.time())

        room.commit()
        return room

    @classmethod
    def query_one(cls, **kwargs):
        """
        :return:
        """
        rec = cls.query(**kwargs)

        return cls(**rec[0])

    @classmethod
    def join(cls, room_code):
        """ 加入房间
        :param room_code:
        :return:
        """
        room = cls.query_one(code=room_code)
        if not room:
            raise Exception('房间不存在')

        room.user_id = uuid.uuid4().hex[:8]
        if not room.user_a:
            room.user_a = room.user_id
        elif not room.user_b:
            room.user_b = room.user_id
        else:
            raise Exception('房间已满员')

        room.commit()

        return room


class RoomRecording(OrmModel):
    """
    """
    __tablename__ = 'room_recording'
    id: int = Field(0, title='id')
    room_code: int = Field(0, title='房间号')
    recording_id: str = Field('', title='录制id')

    @classmethod
    def add(cls, **kwargs):
        """
        :return:
        """
        room = cls(**kwargs)

        room.commit()


if __name__ == "__main__":
    """
    """
    # room = Room.add(name='房间3')
    #
    # rec = Room.query_one(code=room.code)
    # print(rec.model_dump())

    # rec = RoomRecording.create(room_code=12345, recording_id='test')
    # time.sleep(1)
    # room = Room.create(name='房间2')
    # time.sleep(1)
    # room = Room.create(name='房间3')
    # time.sleep(1)
    # room = Room.create(name='房间4')

    # print(room.model_dump())
    # data = ApiRoom.success(data=room.model_dump())
    # room = Room.query_one(room_id=1)

    # Room.join(1762764206)

    # room = Room.query_one(code=1762616679)
    #
    # print(room.model_dump())





